package com.njwb.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    private static ThreadLocal<SqlSession> sqlSessionThreadLocal = new ThreadLocal<>() ;
    private static SqlSessionFactory sqlSessionFactory ;

    static{
        //SqlSessionFactory对象是一个重量级的组件，该组件最好在一个工程中只创建一次。开销比较大，可以将此对象看成Datasource对象
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream) ;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static SqlSession getSqlSession(){
        SqlSession sqlSession = sqlSessionThreadLocal.get();
        if(sqlSession==null) {
            sqlSession = sqlSessionFactory.openSession();
            sqlSessionThreadLocal.set(sqlSession);
        }
        return sqlSession ;
    }


    public static void closeSqlsession(){
        SqlSession sqlSession = sqlSessionThreadLocal.get();
        if(sqlSession!=null) {
            sqlSession.close();
            sqlSessionThreadLocal.remove();
        }
    }


}
